<?php
/**
 * (model) 备货sku（全站点）
 */
namespace App\Models\SsBasic;

use App\Models\Basics\SysCountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use App\Models\ProductStockup\Stockup;
use App\Models\Shipping\SSku;
use App\Models\Shipping\SSkuApply;
use App\Models\Stocking\StockingSetDate;
use App\Models\Stocking\StockingSku;
use Illuminate\Database\Eloquent\Model;
class AreaSku extends Model
{
    protected $table = 's_area_sku';

    protected $guarded = [];

    public static $_type = [
        1 => '系统同步',
        2 => '手工新建'
    ];

    public function stocking_sku(){
        return $this->hasOne(StockingSku::class,'area_psku','area_psku');
    }

    public function shipping_sku(){
        return $this->hasOne(SSku::class,'area_psku','area_psku');
    }

    public function stockup(){
        return $this->hasOne(Stockup::class,'area_psku','area_psku');
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            $model->stocking_sku()->delete();
            $model->shipping_sku()->delete();
        });
    }

    /**
     * 获取最快可售天数 仓库发货7天，预留7天时间
     * @param $pCycle
     * @param $transportDay
     * @return int
     */
    public static function getAvailable($pCycle,$transportDay){
        return $pCycle + $transportDay + 15;
    }

    /**
     * 获取发货库存系数 仓库发货7天，预留7天时间
     * @param $transportDay
     * @return float
     */
    public static function getShipFactor($transportDay){
        return round(($transportDay + 15) / 30,3);
    }

    /**
     * 获取备货库存系数 仓库发货7天，预留7天时间
     * @param $pCycle
     * @param $transportDay
     * @return float
     */
    public static function getStockFactor($pCycle,$transportDay){
        return round(($pCycle + $transportDay + 15) / 30,3);
    }

    /**
     * 获取提货库存系数
     * @param $pCycle
     * @param $transportDay
     * @return float
     */
    public static function getSSkuFactor($pCycle,$transportDay){
        return round(($pCycle + $transportDay + 10) / 30,3);
    }

    /**
     * 添加备货，提货基础数据
     * @param $areaId
     * @param $pSkuId
     * @param $airDay
     * @param $seaDay
     * @param $pCycle
     * @param $unitPrice
     */
    public static function addAreaSku($areaId,$pSkuId,$airDay,$seaDay,$pCycle,$unitPrice){
        $key = $areaId.'_'.$pSkuId;
        $classifyId = ProductSku::getValueById($pSkuId,'classify_id');
        $count = self::query()->where('area_psku',$key)->count();
        if($count == 0){
            self::query()->create(['area_psku' => $key,'type' => 1]);
            $avg = AreaSkuAvg::query()->firstOrCreate(['area_psku' => $key]);
            $estimate = AreaSkuEstimate::query()->firstOrCreate(['area_psku' => $key]);
            $stock = AreaSkuStock::query()->firstOrCreate(['area_psku' => $key]);
            $stockItem = [
                'fba_instant_num' => intval($stock->fba_instant_num) ?: 0,
                'fba_transit_num' => intval($stock->fba_transit_num) ?: 0,
                'cn_instant_num' => intval($stock->cn_instant_num) ?: 0,
                'cn_transit_num' => intval($stock->cn_transit_num) ?: 0,
                'os_instant_num' => intval($stock->os_instant_num) ?: 0,
                'os_transit_num' => intval($stock->os_transit_num) ?: 0,
            ];
            $estimateItem = [];
            for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM - 1;$i++){
                $num = $estimate->{'estimate_num'.$i} ?? 0; //赋值
                $estimateItem['estimate_num'.$i] = intval($num);
            }
            $avgItem = [
                'avg3' => $avg->avg3 ?: 0,
                'avg7' => $avg->avg7 ?: 0,
                'avg15' => $avg->avg15 ?: 0,
                'avg30' => $avg->avg30 ?: 0,
                'avg' => $avg->avg ?: 0,
            ];
            $seaSaleDays = self::getAvailable($pCycle,$seaDay);
            $item = [
                'area_id' => $areaId,
                'psku_id' => $pSkuId,
                'classify_id' => $classifyId,
                'purchase_cycle' => $pCycle, //采购周期
                'unit_price' => $unitPrice, //单位价格
                'air_day' => $airDay, //空运天数
                'air_available' => self::getAvailable($pCycle,$airDay), //空运最快可售日期
                'air_ship_factor' => self::getShipFactor($airDay), //空运发货库存系数
                'air_stock_factor' => self::getStockFactor($pCycle,$airDay), //空运备货库存系数
                'sea_day' => $seaDay, //海运天数
                'sea_available' => $seaSaleDays, //海运最快可售日期
                'sea_ship_factor' => self::getShipFactor($seaDay), //海运发货库存系数
                'sea_stock_factor' => self::getStockFactor($pCycle,$seaDay), //海运备货库存系数
                'set_date' => StockingSetDate::getSetDate($areaId,$classifyId,$seaSaleDays) //设置备货日期
            ];
            //备货sku
            $stockingSku = StockingSku::query()->firstOrNew(['area_psku' => $key],array_merge($item,$avgItem,$estimateItem,$stockItem));
            $stockingSku->over_stock = StockingSku::getOverStock($stockingSku); //积压库存
            $stockingSku->over_stock_value = StockingSku::getOverStockValue($stockingSku->over_stock,$unitPrice); //积压货值
            $stockingSku->save();

            //提货sku
            SSku::query()->updateOrCreate(
                ['area_psku' => $key],
                [
                    'area_id' => $areaId,
                    'psku_id' => $pSkuId,
                    'classify_id' => $classifyId,
                    'purchase_cycle' => $pCycle,
                    'air_day' => $airDay,
                    'air_factor' => self::getSSkuFactor($pCycle,$airDay),
                    'sea_day' => $seaDay,
                    'sea_factor' => self::getSSkuFactor($pCycle,$seaDay),
                ]
            );

            //提货申请
            $shippingDate = SSkuApply::initShippingDate();
            foreach ($shippingDate as $date => $label){
                $_ssaCount = SSkuApply::query()
                    ->where('area_id',$areaId)
                    ->where('psku_id',$pSkuId)
                    ->where('shipping_date',$date)
                    ->count();
                if($_ssaCount == 0){
                    SSkuApply::query()->create([
                        'area_id' => $areaId,
                        'psku_id' => $pSkuId,
                        'shipping_date' => $date
                    ]);
                }
            }
        }else{
            $areaSku = self::query()->where('area_psku',$key)->first();
            if($areaSku->type == 2){
                $areaSku->type = 1;
                $areaSku->save();

                $avg = AreaSkuAvg::query()->firstOrCreate(['area_psku' => $key]);
                $estimate = AreaSkuEstimate::query()->firstOrCreate(['area_psku' => $key]);
                $stock = AreaSkuStock::query()->firstOrCreate(['area_psku' => $key]);

                //备货sku
                $ss = StockingSku::query()->where('area_psku',$key)->first();
                $ss->area_id = $areaId;
                $ss->psku_id = $pSkuId;
                $ss->classify_id = $classifyId;
                $ss->fba_instant_num = intval($stock->fba_instant_num) ?? 0;
                $ss->fba_transit_num = intval($stock->fba_transit_num) ?? 0;
                $ss->cn_instant_num = intval($stock->cn_instant_num) ?? 0;
                $ss->cn_transit_num = intval($stock->cn_transit_num) ?? 0;
                $ss->os_instant_num = intval($stock->os_instant_num) ?? 0;
                $ss->os_transit_num = intval($stock->os_transit_num) ?? 0;
                for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM - 1;$i++){
                    $num = $estimate->{'estimate_num'.$i} ?? 0; //赋值
                    $ss->{'estimate_num'.$i} = intval($num);
                }
                $ss->avg3 = $avg->avg3 ?? 0;
                $ss->avg7 = $avg->avg7 ?? 0;
                $ss->avg15 = $avg->avg15 ?? 0;
                $ss->avg30 = $avg->avg30 ?? 0;
                $ss->avg = $avg->avg ?? 0;
                $ss->unit_price = $unitPrice;
                $ss->purchase_cycle = $pCycle;
                $ss->save();
                $ss->over_stock = StockingSku::getOverStock($ss);
                $ss->over_stock_value = StockingSku::getOverStockValue($ss->over_stock,$unitPrice);
                $ss->save();

                //提货sku
                $sSku = SSku::query()->where('area_psku',$key)->first();
                if(!$sSku){
                    SSku::query()->create([
                        'area_psku' => $key,
                        'area_id' => $areaId,
                        'psku_id' => $pSkuId,
                        'classify_id' => $classifyId,
                        'purchase_cycle' => $pCycle,
                        'air_day' => $airDay,
                        'air_factor' => self::getSSkuFactor($pCycle,$airDay),
                        'sea_day' => $seaDay,
                        'sea_factor' => self::getSSkuFactor($pCycle,$seaDay),
                    ]);
                    //提货申请
                    $shippingDate = SSkuApply::initShippingDate();
                    foreach ($shippingDate as $date => $label){
                        $_ssaCount = SSkuApply::query()
                            ->where('area_id',$areaId)
                            ->where('psku_id',$pSkuId)
                            ->where('shipping_date',$date)
                            ->count();
                        if($_ssaCount == 0){
                            SSkuApply::query()->create([
                                'area_id' => $areaId,
                                'psku_id' => $pSkuId,
                                'shipping_date' => $date
                            ]);
                        }
                    }
                }
            }else{

                //依据sku产品状态,停用备货/提货产品
                //$countryId = SysCountry::getCountryIdsByAreaId($areaId);
                //if ($countryId) {
                //    $maxStatus = ProductAmazonSku::query()
                //        ->where('psku_id',$pSkuId)
                //        ->whereIn('country_id',$countryId)
                //        ->max('status');
                //    //产品停用
                //    if ($maxStatus && $maxStatus == 2) {
                //        $stockingSku = StockingSku::query()->where('area_psku',$key)->first();
                //        if($stockingSku){
                //            $stockingSku->enable_status = 0; //是否启用,1：Y 0：N
                //            $stockingSku->save();
                //        }
                //
                //        $sSku = SSku::query()->where('area_psku',$key)->first();
                //        if($sSku){
                //            $sSku->enable_status = 0; //是否启用,1：Y 0：N
                //            $sSku->save();
                //        }
                //    }
                //}

                //备货sku
                $stockingSku = StockingSku::query()->where('area_psku',$key)->first();
                if($stockingSku){
                    if($stockingSku->enable_status != 1){
                        $stockingSku->enable_status = 1; //是否启用,1：Y 0：N
                        $stockingSku->save();
                    }
                }
                //提货sku
                $sSku = SSku::query()->where('area_psku',$key)->first();
                if($sSku){
                    if($sSku->enable_status != 1){
                        $sSku->enable_status = 1; //是否启用,1：Y 0：N
                        $sSku->save();
                    }
                }

            }
        }
    }

    /**
     * 补数据 (站点sku)
     * @param $areaId
     * @param $pSkuId
     * @param $airDay
     * @param $seaDay
     * @param $pCycle
     * @param $unitPrice
     */
    public static function addAreaSkuData($areaId,$pSkuId,$airDay,$seaDay,$pCycle,$unitPrice){
        $key = $areaId.'_'.$pSkuId;
        $areaSku = self::query()->where('area_psku',$key)->first();
        if($areaSku->type == 2){
            $areaSku->type = 1;
            $areaSku->save();
        }
        $avg = AreaSkuAvg::query()->firstOrCreate(['area_psku' => $key]);
        $estimate = AreaSkuEstimate::query()->firstOrCreate(['area_psku' => $key]);
        $stock = AreaSkuStock::query()->firstOrCreate(['area_psku' => $key]);
        $stockItem = [
            'fba_instant_num' => $stock->fba_instant_num ?: 0,
            'fba_transit_num' => $stock->fba_transit_num ?: 0,
            'cn_instant_num' => $stock->cn_instant_num ?: 0,
            'cn_transit_num' => $stock->cn_transit_num ?: 0,
            'os_instant_num' => $stock->os_instant_num ?: 0,
            'os_transit_num' => $stock->os_transit_num ?: 0,
        ];
        $estimateItem = [];
        for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM - 1;$i++){
            $num = $estimate->{'estimate_num'.$i} ?? 0; //赋值
            $estimateItem['estimate_num'.$i] = intval($num);
        }
        $avgItem = [
            'avg3' => $avg->avg3 ?: 0,
            'avg7' => $avg->avg7 ?: 0,
            'avg15' => $avg->avg15 ?: 0,
            'avg30' => $avg->avg30 ?: 0,
            'avg' => $avg->avg ?: 0,
        ];
        $classifyId = ProductSku::getValueById($pSkuId,'classify_id');
        $seaSaleDays = self::getAvailable($pCycle,$seaDay);
        $item = [
            'area_id' => $areaId,
            'psku_id' => $pSkuId,
            'purchase_cycle' => $pCycle,
            'unit_price' => $unitPrice,
            'air_day' => $airDay,
            'air_available' => self::getAvailable($pCycle,$airDay),
            'air_ship_factor' => self::getShipFactor($airDay),
            'air_stock_factor' => self::getStockFactor($pCycle,$airDay),
            'sea_day' => $seaDay,
            'sea_available' => $seaSaleDays,
            'sea_ship_factor' => self::getShipFactor($seaDay),
            'sea_stock_factor' => self::getStockFactor($pCycle,$seaDay),
            'set_date' => StockingSetDate::getSetDate($areaId,$classifyId,$seaSaleDays)
        ];
        //备货sku
        $stockingSku = StockingSku::query()->firstOrNew(['area_psku' => $key],array_merge($item,$avgItem,$estimateItem,$stockItem));
        $stockingSku->over_stock = StockingSku::getOverStock($stockingSku);
        $stockingSku->over_stock_value = StockingSku::getOverStockValue($stockingSku->over_stock,$unitPrice);
        $stockingSku->save();

        //提货sku
        $sSku = SSku::query()->where('area_psku',$key)->first();
        if(!$sSku){
            SSku::query()->create([
                'area_psku' => $key,
                'area_id' => $areaId,
                'psku_id' => $pSkuId,
                'purchase_cycle' => $pCycle,
                'air_day' => $airDay,
                'air_factor' => self::getSSkuFactor($pCycle,$airDay),
                'sea_day' => $seaDay,
                'sea_factor' => self::getSSkuFactor($pCycle,$seaDay),
            ]);
            $shippingDate = SSkuApply::initShippingDate();
            foreach ($shippingDate as $date => $label){
                $_ssaCount = SSkuApply::query()
                    ->where('area_id',$areaId)
                    ->where('psku_id',$pSkuId)
                    ->where('shipping_date',$date)
                    ->count();
                if($_ssaCount == 0){
                    SSkuApply::query()->create([
                        'area_id' => $areaId,
                        'psku_id' => $pSkuId,
                        'shipping_date' => $date
                    ]);
                }
            }
        }
    }

}
